package com.blade.jmm;

import java.util.ArrayList;
import java.util.List;

/**
 * ClassName: VolatileVisibilitySample
 * Description: 可见性demo
 * 详细介绍见我的博客链接
 * https://blog.csdn.net/weixin_44218060/article/details/111464800
 *
 * @author blade
 * @version 1.0
 * @Date 2020/12/20 21:37
 */
public class VolatileVisibilitySample {
    /**
     * 全局成员变量
     */
    private boolean initFlag = false;
    List<Integer> a = new ArrayList<>();
    static Object object = new Object();

    public void refresh(){
        this.initFlag = true; //普通写操作，(volatile写)
        String threadname = Thread.currentThread().getName();
        System.out.println("线程："+threadname+":修改共享变量initFlag");
    }

    public void load(){
        String threadname = Thread.currentThread().getName();
        int i = 0;
        while (!initFlag){
//            synchronized (object){
//                i++;
//            }
            i++;
//            System.out.println(i);
//            a.add(i);

        }
        System.out.println("线程："+threadname+"当前线程嗅探到initFlag的状态的改变"+i+initFlag);
    }

    public static void main(String[] args){
        VolatileVisibilitySample sample = new VolatileVisibilitySample();
        Thread threadA = new Thread(()->{
            sample.refresh();
        },"threadA");

        Thread threadB = new Thread(()->{
            sample.load();
        },"threadB");

        threadB.start();
        /**
         * 这个睡眠必须加，不加的话，如果不保证执行完
         */
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        threadA.start();
    }
}
